package org.dragonnova.lamp;

import java.util.Collection;
import java.util.TreeMap;

/**
 * Created by hucn on 2016/10/27.
 * Description:
 */
public class LampGroup {

    private int group;

    private String ip;

    private int size;

    private TreeMap<Integer, Lamp> members;

    private byte[] status;

    public LampGroup(int group, String ip, int size) {
        this.group = group;
        this.ip = ip;
        this.size = size;
        this.members = new TreeMap<>();
        for (int i = 0; i < size; i++) {
            Lamp lamp = new Lamp();
            lamp.setGroup(group);
            lamp.setStatus(Lamp.OFF);
            lamp.setIp(ip);
            lamp.setId(i);
            lamp.setName("no_name");
            members.put(i, lamp);
        }
        status = new byte[]{0x00, 0x00};
    }

    public int getGroup() {
        return group;
    }

    public void setGroup(int group) {
        this.group = group;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public TreeMap<Integer, Lamp> getMembers() {
        return members;
    }

    public void setMembers(TreeMap<Integer, Lamp> members) {
        this.members = members;
    }

    public void refresh(byte[] statusBytes) {
        if (statusBytes == null || statusBytes.length != 2) {
            return;
        }
        status = statusBytes;
        for (int i = 0; i < size; i++) {
            if (i <= 7) {
                int status = ((statusBytes[1] >> i) & 0x01);
                members.get(i).setStatus(status == 0 ? Lamp.OFF : Lamp.ON);
            } else {
                int j = i - 8;
                int status = ((statusBytes[0] >> j) & 0x01);
                members.get(i).setStatus(status == 0 ? Lamp.OFF : Lamp.ON);
            }
        }
    }

    public Collection<? extends Lamp> getLamps() {
        return members.values();
    }

    public byte[] getStatus() {
        return status;
    }

    public void setStatus(byte[] status) {
        this.status = status;
    }
}
